import api from '@/api/index.js';
import {redirect} from "react-router-dom"
import  store from "@/store/index.js";
import {userActions} from '@/store/actions/userAction.js';
import {saveData} from "@/utils/localstorage.js";

export default async function updataAction({request}) {
    const formData = await request.formData();
    //获取表单字段
    const username = formData.get("username");
    const password = formData.get("password");


//     数据校验
    const errors = {};
    if (typeof username !== "string" || username.length < 3) {
        errors.username = "请输入字符长度大于3位的用户名";
    }
    if (typeof password !== "string" || password.length < 6) {
        errors.password = "请输入字符长度大于6位的密码";
    }
    if (Object.keys(errors).length) return errors;
// 创建账号
    const updataUser = Object.fromEntries(formData);
    const response = await api.user.updata(updataUser);
    console.log(response)
    if (response && response.status !== 1) {
        throw new Error(response.message);
    }
    // 获取更新成功字段
    const {status,message,data} = response;
    // 更新store
    // 同步到store
    const  currentUser = data;
    store.dispatch(userActions(currentUser))
    //同步到localstorage
    saveData("currentUser",currentUser)
    // 重定向到首页
    return {status,message};
}